#include "qkeyboardwidget.h"

#include <QPainter>
#include <QStyleOption>
#include <QApplication>
#include <QKeyEvent>
#include <QPushButton>

QKeyBoardWidget::QKeyBoardWidget(QWidget *parent) :
    QWidget(parent),
    m_focus_widget(NULL)
{
}

void QKeyBoardWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    QStyleOption opt;
    opt.initFrom(this);
    style()->drawPrimitive( QStyle::PE_Widget, &opt, &painter, this);
}

void QKeyBoardWidget::set_focus_widget(QWidget *widget)
{
    set_cap(false);
    set_shift(false);
    m_focus_widget=widget;
}

void QKeyBoardWidget::send_key(int key)
{
    if(m_focus_widget!=NULL)
    {
        if(key==Qt::Key_Shift)
        {
            set_shift(!m_is_shift);
        }
        else if(key==Qt::Key_CapsLock)
        {
            set_cap(!m_is_cap);
        }
        else
        {
            QChar c(key);

            bool temp=m_is_shift;
            if(m_is_cap)temp=!temp;
            if(temp)
            {
                c=c.toUpper();
            }
            else
            {
                c=c.toLower();
            }
            QKeyEvent press(QEvent::KeyPress,key,Qt::NoModifier,c.isPrint()?QString(c):"");
            qApp->sendEvent(m_focus_widget,&press);
            QKeyEvent release(QEvent::KeyRelease,key,Qt::NoModifier);
            qApp->sendEvent(m_focus_widget,&release);
            set_shift(false);
        }
    }
}

void QKeyBoardWidget::set_cap(bool cap)
{
    if(m_is_cap!=cap)
    {
        QObjectList list=children();
        m_is_cap=cap;
        while(list.size()>0)
        {
            QWidget* wid=qobject_cast<QWidget*>(list.takeFirst());
            if(wid!=NULL)
            {
                if(wid->inherits("QPushButton") && wid->property("key").toInt()==Qt::Key_CapsLock)
                {
                    ((QPushButton*)wid)->setCheckable(true);
                    ((QPushButton*)wid)->setChecked(m_is_cap);
                }
            }
        }
    }
}

void QKeyBoardWidget::set_shift(bool shift)
{
    if(m_is_shift!=shift)
    {
        QObjectList list=children();
        m_is_shift=shift;
        while(list.size()>0)
        {
            QWidget* wid=qobject_cast<QWidget*>(list.takeFirst());
            if(wid!=NULL)
            {
                if(wid->inherits("QPushButton") && wid->property("key").toInt()==Qt::Key_Shift)
                {
                    ((QPushButton*)wid)->setCheckable(true);
                    ((QPushButton*)wid)->setChecked(m_is_shift);
                }
            }
        }
    }
}
